package com.crm.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.sql.Timestamp;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import net.sf.json.JsonConfig;

public class ResponseUtils {
	
	private static Logger logger = Logger.getLogger(ResponseUtils.class);
	
	public static void printHtml(HttpServletResponse response, String value) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(value);
		} catch (IOException e) {
			logger.error(e);
		} finally {
			if (out != null)
				out.close();
		}
	}
	
	public static void printString(HttpServletResponse response, String value) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(value);
		} catch (IOException e) {
			logger.error(e);
		} finally {
			if (out != null)
				out.close();
		}
	}

	public static void printJson(HttpServletResponse response, String value) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/json");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(value);
		} catch (IOException e) {
			logger.error(e);
		} finally {
			if (out != null)
				out.close();
		}
	}

	public static void printJson(HttpServletResponse response, String key,
			Object object, String dateFormat, String[] excludes) {
		PrintWriter out = null;
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/json");
		try {
			out = response.getWriter();
			JsonConfig jsonConfig = new JsonConfig();

			if ((excludes != null) && (excludes.length != 0)) {
				jsonConfig.setExcludes(excludes);
			}

			if (("".equals(dateFormat)) || (dateFormat == null)) {
				jsonConfig.registerJsonValueProcessor(Date.class,
						new JsonUtil.JsonDateValueProcessor());
				jsonConfig.registerJsonValueProcessor(Timestamp.class,
						new JsonUtil.JsonDateValueProcessor());
			} else {
				jsonConfig.registerJsonValueProcessor(Date.class,
						new JsonUtil.JsonDateValueProcessor(dateFormat));
				jsonConfig.registerJsonValueProcessor(Timestamp.class,
						new JsonUtil.JsonDateValueProcessor(dateFormat));
			}
			String jsonStr = JsonUtil.beanToJson(object, jsonConfig);

			if (key != null) {
				jsonStr = "{\"" + key + "\":" + jsonStr + "}";
			}
			out.print(jsonStr);
		} catch (IOException e) {
			logger.error(e);
		} finally {
			if (out != null)
				out.close();
		}
	}
}